<template>
  <div class="jnpf-content-wrapper bg-white">
    <div class="jnpf-content-wrapper-center" v-loading="loading">
      <IlmsWrapperHead
        :title="projectInfo?.contractName || '内部分包和委托'"
        :versionList="versionList"
        @versionClick="versionClick"
      >
        <!-- 有按钮权限 && 不处于变更版本 && -->
        <template v-if="canAddNeed && !isNewVersion && isMine" #toolbar>
          <a-button type="primary" @click="toAddedNeed">
            <template #icon>
              <PlusOutlined />
            </template>
            变更
          </a-button>
        </template>
      </IlmsWrapperHead>

      <div class="jnpf-content-wrapper-center-content allContent-eare">
        <a-steps
          :current="current"
          type="navigation"
          size="small"
          :style="{ boxShadow: '0px -1px 0 0 #e8e8e8 inset' }"
          @change="stepChange"
        >
          <a-step :status="stepStatus[0]" title="分配合同交付清单任务" />
          <a-step :status="stepStatus[1]" title="确认任务分配情况" />
        </a-steps>
        <!-- 内容 -->
        <div class="content-eare">
          <div v-show="current == 0" class="h-full">
            <DeliveryList ref="deliveryListRef" @initTasks="initConfirmTask"/>
          </div>
          <ConfirmTask
            ref="confirmTaskRef"
            v-show="current == 1"
            class="h-full"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script name="internalOperations" setup>
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { spStatusEnum } from '@/utils/spStatus';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import { useProjectStore } from '@/store/modules/project';
  import { historyListJSJ } from '@/views/project/internalOperations/common/formConfig';
  import { getContractInfoByCode, getPackageTrustList, historyContractList } from '@/views/project/internalOperations/common/api'; 
  // 改为绝对路径无法引入
  import DeliveryList from './components/deliveryList.vue';
  import ConfirmTask from './components/confirmTask.vue';

  const { getUserInfo } = useUserStore();
  const { createMessage } = useMessage();

  const emitter = inject('emitter');
  const projectStore = useProjectStore();
  const { projectInfo } = storeToRefs(projectStore);
  const { toggleProjectSelect } = projectStore;

  const loading = ref(false);
  const deliveryListRef = ref(), confirmTaskRef = ref();
  const historyList = ref([]);
  const isNewVersion = ref(false), // 是否是添加新版本
        lastVersion = ref(true); // 是否是最新版本
  const current = ref(0),
        signAType = ref(''), // 合同甲方签署单位
        signBType = ref(''), // 合同乙方签署单位
        isMine = ref(false), // 当前登录人是否是负责人
        contractCode = ref('');
  const stepStatus = reactive(['process', 'wait']);

  const stepChange = index => {
    if(index==0 && deliveryListRef.value.canReturn){
      initDeliveryList();
      current.value = index;
    }else if(index==0){
      createMessage.warning('该合同的分包和委托，已经分配并存在提交审批记录！');
    };
    if(index==1) deliveryListRef.value.saveTasks();
  };
  
  const initContractSelect = () => {
    toggleProjectSelect(true, {
      fieldNames: {
        label: 'contractName',
        value: 'contractCode',
      },
      searchInfo: {
        contractSpStatus: 2,
      },
    });
  };

  initContractSelect();

  onActivated(() => {
    initContractSelect();
  });
  
  // 获取审批状态对应文本
  const getSpStatus = (status, type) => {
    const foundItem = spStatusEnum.find(item => item.value == status);
    return `【${foundItem?.[type]}】` || '';
  };
  
  const versionList = computed(() => {
    return historyList.value.map(item => ({
      label: `分包委托版本：V${item.version}`,
      spStatus: item.spStatus,
      value: item.version,
      color: spStatusEnum[item.spStatus]?.color,
    }));
  });

  const versionClick = (row) => {
    isNewVersion.value = false;
    // 最新版本
    lastVersion.value = historyList.value.length==row.value;
    // 所选版本的数据
    let info = historyList.value[row.value-1];
    if(info.spStatus=='0') { // 审批状态为待提交，刷新页面
      initStep();
    }else{ // 其他审批状态，获取info固定页面到步骤2
      current.value = 1;
      initConfirmTask(info);
    }
  };

  const canAddNeed = computed(() => {
    if(historyList.value?.length > 0){
      return historyList.value[historyList.value.length - 1].spStatus == '2';
    };
    return false;
  });

  // 添加新版本，获取最新交付清单进行分配；
  const toAddedNeed = async () => {
    isNewVersion.value = true;
    initStep();
  };

  const getHistoryList = async (contractCode) => {
    if(!contractCode) return ;
    const res = await historyContractList(contractCode);
    historyList.value = res?.data; // historyListJSJ; // 
  };

  // 获取历史分包和委托的交付清单任务分配数
  const getTotalTaskIdsLength = (info) => {
    let totalTaskIdsLength = 0;
    // 处理委托
    if (info?.contractTrustVoList) {
      info.contractTrustVoList.forEach(item => {
        const materials = item.contractMaterialsTrustVoList || [];
        totalTaskIdsLength += materials.filter(m =>
          m?.parentId === "0" && m?.materialsCode != null
        )?.length;
      });
    }
    // 处理分包
    if (info?.contractPackageVoList) {
      info.contractPackageVoList.forEach(item => {
        const materials = item.contractMaterialsPackageList || [];
        totalTaskIdsLength += materials.filter(m =>
          m?.parentId === "0" && m?.materialsCode != null
        )?.length;
      });
    }
    return totalTaskIdsLength;
  };

  // 获取全部版本数据；判断分配情况，初始化步骤1还是步骤2
  const initStep = async () => {
    loading.value = true;
    try {
      if (projectInfo.value?.contractCode) {
        contractCode.value = projectInfo.value.contractCode;
        // customerManagerId客户经理Id==当前登录人 || projectManagerId项目经理Id==当前登录人
        isMine.value = projectInfo.value.customerManagerId==getUserInfo?.userId || projectInfo.value.projectManagerId==getUserInfo?.userId;
        // 获取数据版本
        getHistoryList(contractCode.value);
        // 初始化步骤值
        const contractRes = await getContractInfoByCode(contractCode.value);
        let info = contractRes?.data;
        signAType.value = info.signAType;
        signBType.value = info.signBType;
        if(isNewVersion.value) {
          current.value = 0;
          initDeliveryList();
          return;
        };
        const totalTaskCount = info?.contractMaterials?.length || 0;
        
        let allocateInfo = (await getPackageTrustList(contractCode.value))?.data || {};
        const totalTaskIdsLength = getTotalTaskIdsLength(allocateInfo);
        // 在步骤2的要求: 全部分配完 || (部分分配&&合同乙方!=外部)
        let pageSteps = totalTaskIdsLength>=totalTaskCount || (totalTaskIdsLength>0 && signBType.value!='1')
        current.value = pageSteps ? 1 : 0;
        // 这里的判断调用步骤初始化
        current.value==0 ? initDeliveryList() : 
        current.value==1 ? initConfirmTask() : '';
      } else {
        await nextTick();
        emitter.emit('openProjectSelectModal', true);
      }
    } finally {
      loading.value = false;
    }
  };

  watch(
    () => projectInfo.value,
    (val)=>{
      isNewVersion.value = false;
      if(val) initStep();
    },
  );

  // 步骤1初始化
  const initDeliveryList = () => {
    deliveryListRef.value.initTable();
  };

  // 步骤2初始化
  const initConfirmTask = (info = null) => {
    confirmTaskRef.value.initTasks(info);
  };

  onMounted(() => {
    initStep();
  });

  // 给子孙组件传值
  provide('current', current);
  provide('signAType', signAType);
  provide('signBType', signBType);
  provide('lastVersion', lastVersion);
  provide('isNewVersion', isNewVersion);
  provide('projectInfo', projectInfo);
  provide('initTable', initDeliveryList);
  provide('isMine', isMine);

  // 给子组件暴露所需方法
  defineExpose({
    initConfirmTask,
  });
</script>

<style scoped>
  /* 步骤1高度调整 */
  .allContent-eare {
    height: calc(100% - 60px); /* 所占高度减去历史版本高度 */
    display: flex;
    flex-direction: column;

    .content-eare {
      flex: 1;
      min-height: 0;
    }
  }
</style>
